angular.module('starter')
.controller("payment_methodCtrl",function($scope,CountDown,ngAuthSettings,appBase,$state, authService, httpService, UserInfo){
	//更多方式
	var w=null;
	var PAYSERVER=ngAuthSettings.apiServiceBaseUrl+httpService.appWebApi.payment;
	var pays={};
	
	$scope.routeBol = false;
	$scope.handleBol = true;
	$scope.moreRoute = function(){
		if($scope.handleBol){
			$scope.routeBol = true;
			$scope.handleBol = false;
		}else{
			$scope.routeBol = false;
			$scope.handleBol = true;
		}
	}

	initialize();
	
	appplus(function(){
	// 获取支付通道
	plus.payment.getChannels(function(channels){
		for(var i in channels){
			var channel=channels[i];
			if(channel.id=='qhpay'||channel.id=='qihoo'){	// 过滤掉不支持的支付通道：暂不支持360相关支付
				continue;
			}
			pays[channel.id]=channel;
		}
	},function(e){
		plus.nativeUI.alert('获取支付通道失败'+e.message);
	});
		
	});
	
	    //初始化
	function initialize() {
 
	    var orderData = angular.fromJson(localStorage.getItem("orderData")) || [];
	    $scope.DoctorParma = orderData.DoctorParma;
	    $scope.UserInfo = orderData.UserInfo;
	    $scope.Hospital = orderData.Hospital;
	    $scope.reInfo = orderData.reInfo;
	}
 
 
$scope.payfn=function(){
//	 backorder();
//	 return;
	if(w){return;}//检查是否请求订单中
	
	var id="alipay";
	if(document.getElementById('weixin').checked)
	{
		id="wxpay";
	}
 
	var url=PAYSERVER;
	if(id=='alipay'||id=='wxpay'){
		url+=id;
	}else{
		plus.nativeUI.alert('当前环境不支持此支付通道！', null, '提醒');
		return;
	}
	console.log(url);
 
	// 请求支付订单
	url+='&orderid='+$scope.reInfo.orderId;
	w=plus.nativeUI.showWaiting();
 
	var xhr=new XMLHttpRequest();
	xhr.onreadystatechange=function(){
		switch(xhr.readyState){
			case 4:
			w.close();w=null;
			if(xhr.status==200){
				var order=xhr.responseText;
				console.log(order);
				plus.payment.request(pays[id],order,function(result){
 					CountDown.clear(); //清理倒计时
 					var boolresult=true; 
 					var paydata={};
 					if(result.channel.id=="alipay")
 					{
 					 paydata=JSON.parse(JSON.parse(result.rawdata).result).alipay_trade_app_pay_response;
	 				 boolresult= RegOrder("alipay",paydata.out_trade_no,paydata.trade_no,"");
 				   }else
 				   {
						 			//微信的待写	   	
 				   }
		 
				},function(e){
 
					plus.nativeUI.alert('更多错误信息请参考支付(Payment)', null, '支付失败：'+e.code);
				});
			}else{
				plus.nativeUI.alert('获取订单信息失败！', null, '提醒');
			}
			break;
			default:
			break;
		}
	}
	xhr.open('GET',url);
//	outLine('请求支付订单：'+url+amount);
	xhr.send();
}

	function backorder(msg)
	{
        updateorderstatus(msg);
		$state.go('paymentRoute');
		return;
	}
	
	//更新订单信息
	function updateorderstatus(msg)
	{
		 var orderData = angular.fromJson(localStorage.getItem("orderData")) || [];       
       	orderData.DoctorParma.status=msg;//"PAYED";
        localStorage.setItem("orderData", angular.toJson(orderData));
	}

	/// 当天支付
	function RegOrder(payMode,orderPayId,order_prepay_id,transaction_id)
	{
 		if($scope.DoctorParma.type==2)
 		{
			 plus.nativeUI.alert('支付成功',function(){
				backorder("PAYED");
			},'提醒');
			return  true; 			
 		}
		var parData = {};
        parData.hospitalCode=$scope.Hospital.hspCode;
        parData.lock_no=$scope.reInfo.lockId;
        parData.orderId=$scope.reInfo.orderId;
        parData.hisOrderId=$scope.reInfo.hisOrderId;
        parData.patMedNo=$scope.UserInfo.hisCardNumber;
        parData.patName=$scope.UserInfo.DisplayName;
        parData.patIdCard=$scope.UserInfo.idCard;
        parData.operMobile=$scope.UserInfo.Tel;
        parData.patMobile=$scope.UserInfo.Tel;
        parData.fee=$scope.DoctorParma.regFee;
        parData.treatfee=$scope.DoctorParma.treatFee;
        parData.orderPayId=orderPayId;
        parData.orderType="APP";
        parData.payMode=payMode;
        parData.order_amount=(parseInt($scope.DoctorParma.treatFee) + parseInt($scope.DoctorParma.regFee));
        parData.order_prepay_id=order_prepay_id;
        parData.transaction_id=transaction_id;
        parData.out_trade_no=orderPayId
 
      
      //预约当天的付款
            httpService.post(httpService.appWebApi.RegOrderToday,
              parData
              ).then(
              function (success) {
                  var data = success.data;
                  if (data.returnCode != "0") {
                      console.log(data.returnMsg);
                      plus.nativeUI.alert('支付失败'+data.returnMsg,function(){
                  	backorder("CANCEL");
                  },"提醒");
                  }else
                  {
              	plus.nativeUI.alert('支付成功：感谢你的支持，我们会继续努力完善产品。',function(){
					backorder("PAYED");
				},'提醒');
				}
                  return true;
              }
              , function (error) {
                  console.log(error);
                  plus.nativeUI.alert('支付失败'+error.Message,function(){
                  	backorder("CANCEL");
                  },"提醒");
                  return false;
              });
       
	}
});